package com.xn.myyxcampus.fragment;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.audiofx.LoudnessEnhancer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.xn.myyxcampus.LoadingActivity;
import com.xn.myyxcampus.R;
import com.xn.myyxcampus.http.URLs;
import com.xn.myyxcampus.utils.AnimUtils;
import com.xn.myyxcampus.utils.FileHelper;
import com.xn.myyxcampus.utils.ImageUtils;
import com.xn.myyxcampus.utils.MD5;
import com.xn.myyxcampus.utils.MyPreferences;
import com.xn.myyxcampus.utils.ToastUtils;
import com.xn.myyxcampus.utils.VerifyUtil;

public class RegisterFragment extends BaseFragment implements OnClickListener {

	public String LEFT_HEAD_DIR_NAME = Environment
			.getExternalStorageDirectory() + "/DCIM/Tracy/HeadPhoto";
	public String RIGISTER_HEAD_DIR_NAME = Environment
			.getExternalStorageDirectory() + "/DCIM/Tracy/Rigister";

	public File LEFT_HEAD_DIR = new File(LEFT_HEAD_DIR_NAME);
	public File RIGISTER_HEAD_DIR = new File(RIGISTER_HEAD_DIR_NAME);
	private RelativeLayout postImage;
	private ImageView imageHead;
	private EditText userName;
	private EditText userPass;
	private EditText userEmail;
	private ImageView loading;
	private Button register;
	private ImageView show;
	private ObjectMapper objectMapper = new ObjectMapper();

	private static final int ICON_SIZE = 300;
	/*** The launch code when picking a photo and the raw data is returned */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	/*** The launch code when taking a picture */
	private static final int CAMERA_WITH_DATA = 3023;

	HttpUtils httpUtil = new HttpUtils();

	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.register, null);
		postImage = (RelativeLayout) view.findViewById(R.id.postImage);
		imageHead = (ImageView) view.findViewById(R.id.iv_imageHead);
		userName = (EditText) view.findViewById(R.id.et_reguserName);
		userPass = (EditText) view.findViewById(R.id.et_reguserPass);
		loading = (ImageView) view.findViewById(R.id.iv_regLoading);
		register = (Button) view.findViewById(R.id.b_register);
		show = (ImageView) view.findViewById(R.id.iv_rigshowMenu);
		userEmail = (EditText) view.findViewById(R.id.et_reguserEmail);
		show.setOnClickListener(this);
		register.setOnClickListener(this);
		postImage.setOnClickListener(this);
		return view;
	}

	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

	}

	private String name;
	private String pass;
	private String email;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_rigshowMenu:
			showLeft();
			break;
		case R.id.b_register:


			name = userName.getText().toString().trim();
			pass = MD5.md5(userPass.getText().toString().trim());
			email = userEmail.getText().toString().trim();

			if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)
					|| TextUtils.isEmpty(email)) {
				ToastUtils.showToast("用户名，密码，邮箱不能为空");
				return;
			}

			if (!VerifyUtil.isEmail(email)) {
				ToastUtils.showToast("邮箱格式不正确");
			}

			if (!VerifyUtil.isUser(name)) {
				ToastUtils.showToast("用户名不能为中文哦！");
				return;
			}

			if (!VerifyUtil.isUser(userPass.getText().toString())) {
				ToastUtils.showToast("密码不能为中文!!!");
				return;
			}

			if (userPass.getText().toString().length() < 6) {
				ToastUtils.showToast("密码不能小于六位数");
			}
			RequestParams params = new RequestParams();
			try {
				loading.setVisibility(View.VISIBLE);
				animationDrawable = (AnimationDrawable) loading.getBackground();
				animationDrawable.start();
				params.addBodyParameter("name", new String(name.getBytes(),
						"utf-8"));
				params.addBodyParameter("pwd", pass);
				params.addBodyParameter("email", email);

				if (TextUtils.isEmpty(bitmapName)) {
					params.addBodyParameter("hasFile", "0");
					LogUtils.i("no bit map");
				} else {
					params.addBodyParameter("hasFile", "1");
					LogUtils.i(RIGISTER_HEAD_DIR + File.separator
							+ bitmapName);
					File file = new File(RIGISTER_HEAD_DIR
							+ File.separator + bitmapName);
					params.addBodyParameter("file", file);
				}

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			httpUtil.send(HttpRequest.HttpMethod.POST, URLs.USER_REGISTER,
					params, new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							// TODO Auto-generated method stub
							ToastUtils.showToast("失败");
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							if (null != bitmap
									&& !TextUtils.isEmpty(bitmapName)) {
								if (LEFT_HEAD_DIR.exists()) {
									FileHelper.deleteDir(LEFT_HEAD_DIR);
								}
								
								if(RIGISTER_HEAD_DIR.exists()) {
									FileHelper.deleteDir(RIGISTER_HEAD_DIR);
								}
							}
							
							if(!LEFT_HEAD_DIR.exists()) {
								LEFT_HEAD_DIR.mkdir();
							}
							ImageUtils.putImageToSDcar(bitmap,
									LEFT_HEAD_DIR_NAME + File.separator
											+ bitmapName);
							try {
								LogUtils.i(arg0.result);
								HashMap<String, Object> map = objectMapper
										.readValue(arg0.result, HashMap.class);
								int response = (Integer) map.get("response");
								if (1 == response) {
									ToastUtils.showToast((String) map
											.get("tips"));
									SharedPreferences sp = MyPreferences
											.getShare();
									Editor edit = sp.edit();
									edit.putString("name", name);
									edit.putString("pass", pass);
									edit.putString(MyPreferences.TOKEN,
											(String) map.get("uid"));
									edit.commit();							
									Intent intent = new Intent(getActivity(),
											LoadingActivity.class);
									intent.putExtra("loadTime", 500);
									animationDrawable.stop();
									loading.setVisibility(View.GONE);
									startActivity(intent);
									AnimUtils.scaleIn(getActivity());
									getActivity().finish();
								}
								if(0 == response) {
									ToastUtils.showToast((String) map.get((String)map.get("tips")));
									animationDrawable.stop();
									loading.setVisibility(View.GONE);
								}
							} catch (JsonParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonMappingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
			break;
		case R.id.postImage:
			showPickDialog();
			break;
		}
	}

	private void showPickDialog() {
		new AlertDialog.Builder(getActivity()).setTitle("设置头像....")
				.setNegativeButton("相册", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						doPickPhotoFromGallery();
					}
				})
				.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						doTakePhoto();
					}
				}).show();
	}

	/** 拍照或者取图片后存放的位置 */
	private File mCurrentPhotoFile;
	// 拍照的位图
	private Bitmap bitmap;

	private String bitmapName;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Ignore failed requests
		if (resultCode != (-1))
			return;

		switch (requestCode) {
		case CAMERA_WITH_DATA: {
			doCropPhoto(mCurrentPhotoFile);
		}
			break;
		case PHOTO_PICKED_WITH_DATA:
			// 得到的裁剪后的photo的bitmap对象
			bitmap = data.getParcelableExtra("data");
			bitmapName = getPhotoFileName();
			if(!RIGISTER_HEAD_DIR.exists()) {
				RIGISTER_HEAD_DIR.mkdir();
			}
			ImageUtils.putImageToSDcar(bitmap, RIGISTER_HEAD_DIR
					+ File.separator + bitmapName);
			// headImage.setImageBitmap(bitmap);
			imageHead.setImageBitmap(bitmap);
			break;
		}
	}

	/***
	 * Create a file name for the icon photo using current time.创建图片名称
	 */
	private String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}

	/***
	 * Launches Camera to take a picture and store it in a file.这个方法是启动照相程序
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			File leftHeadFile = new File(LEFT_HEAD_DIR_NAME);
			leftHeadFile.mkdirs();
			mCurrentPhotoFile = new File(leftHeadFile, getPhotoFileName());
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			ToastUtils.showToast("not find photo");
		}
	}

	/***
	 * Constructs an intent for capturing a photo and storing it in a temporary
	 * file.
	 */
	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/***
	 * Sends a newly acquired photo to Gallery for cropping
	 */
	protected void doCropPhoto(File f) {
		try {

			// Add the image to the media store
			Intent intentScan = new Intent(
					Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			getActivity().sendBroadcast(intentScan);
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Log.e("Devdiv", "Cannot crop image");
			ToastUtils.showToast("not find photo");
		}
	}

	/***
	 * Constructs an intent for image cropping.
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/**");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", ICON_SIZE);
		intent.putExtra("outputY", ICON_SIZE);
		intent.putExtra("return-data", true);
		return intent;
	}

	/***
	 * Launches Gallery to pick a photo.
	 */
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			ToastUtils.showToast("not find photo");
		}
	}

	/***
	 * Constructs an intent for picking a photo from Gallery, cropping it and
	 * returning the bitmap.
	 */
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/**");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", ICON_SIZE);
		intent.putExtra("outputY", ICON_SIZE);
		intent.putExtra("return-data", true);
		return intent;
	}
}
